package com.personal.revenant.oulewaimai;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;

import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alipay.sdk.app.PayTask;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.apkfuns.logutils.BuildConfig;
import com.apkfuns.logutils.LogUtils;
import com.igexin.sdk.PushManager;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.compress.OnCompressListener;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.master.permissionhelper.PermissionHelper;
import com.nanchen.compresshelper.CompressHelper;
import com.personal.revenant.oulewaimai.bean.C;
import com.personal.revenant.oulewaimai.bean.Event;
import com.personal.revenant.oulewaimai.bean.MutiltypePhotoResults;
import com.personal.revenant.oulewaimai.bean.PhotoBean;
import com.personal.revenant.oulewaimai.bean.PicBean;
import com.personal.revenant.oulewaimai.bean.UploadImgBean;
import com.personal.revenant.oulewaimai.bean.WxPayParams;
import com.personal.revenant.oulewaimai.event.JsApi;
import com.personal.revenant.oulewaimai.util.GlideEngine;
import com.personal.revenant.oulewaimai.utils.DemoIntentService;
import com.personal.revenant.oulewaimai.utils.DemoPushService;
import com.personal.revenant.oulewaimai.utils.GlideImageLoader;
import com.personal.revenant.oulewaimai.utils.GsonUtil;
import com.personal.revenant.oulewaimai.utils.LoadDialog;
import com.personal.revenant.oulewaimai.utils.PayResult;
import com.personal.revenant.oulewaimai.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.utils.SocializeUtils;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import wendu.dsbridge.DWebView;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;
import static com.personal.revenant.oulewaimai.utils.Constant.ACTION_UPLOAD_HEADIMG;
import static com.personal.revenant.oulewaimai.utils.Constant.BASEURL;
import static com.personal.revenant.oulewaimai.utils.Constant.WXAPP_ID;

public class MainActivity extends Activity implements JsApi.JsCallback, UMShareListener {

    private RelativeLayout loadView;
    private SmartRefreshLayout smartRefreshLayout;
    private boolean firstLoad = true;
    protected LoadDialog loadDialog;
    private AgentWeb mAgentWeb;
    private ProgressDialog dialog;
    private DWebView dWebView;
    private String url;
    private Context context;
    private static final int IMAGE_PICKER = 300;
    private Button button;
    private int REQUEST_CODE_SCAN = 111;
    private PermissionHelper permissionHelper;
    private List<LocalMedia> selectList = new ArrayList<>();
    private String userid;
    private String goodinfo;
    private static final int SDK_PAY_FLAG = 1;
    private SHARE_MEDIA shareMedia;
    private String type;

    private final int REQUEST_UPLOAD_HEADIMG = 10001;// 上传头像
    private String requestUrl;// 请求地址
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, WXAPP_ID);
        EventBus.getDefault().register(this);
        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
        initWight();
//        zhifubao();
//        weixin();
        context = this;
        setContentView(R.layout.activity_main);
        Utils.setImageStatus(this);
        setStatusBg(R.color.colorPrimary);
        url = BASEURL;
        initView();
    }


    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;


    private void initLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
//                    301);//自定义的code
            locationClient = new AMapLocationClient(this.getApplicationContext());
            locationOption = getDefaultOption();
            //设置定位参数
            locationClient.setLocationOption(locationOption);
            // 设置定位监听
            locationClient.setLocationListener(locationListener);

            locationClient.startLocation();
        } else {
            locationClient = new AMapLocationClient(this.getApplicationContext());
            locationOption = getDefaultOption();
            //设置定位参数
            locationClient.setLocationOption(locationOption);
            // 设置定位监听
            locationClient.setLocationListener(locationListener);
            locationClient.startLocation();
        }

    }

    @Override
    public void goNavigate(Object params) {

        if (params == null) {
            return;
        }
        String lat = "";
        String lon = "";
        try {
            JSONObject jsonObject = new JSONObject(params.toString());
            lat = jsonObject.getString("lat");
            lon = jsonObject.getString("lon");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (isAppInstalled(context, "com.autonavi.minimap")) {
            Intent intent2 = new Intent();
            intent2.setAction("android.intent.action.VIEW");
            String stringurl = "androidamap://navi?sourceApplication=appname&poiname=fangheng&lat=" + lat + "&lon=" + lon + "&dev=1&style=2";
            Uri uri = Uri.parse(stringurl);
            intent2.setData(uri);
            startActivity(intent2);
        } else {
            Utils.toast(context, "请安装高德地图");
        }
    }


    private boolean isAppInstalled(Context context, String uri) {
        PackageManager pm = context.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    @Override
    public void getLocation(Object params) {
        initLocation();
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    //定位完成的时间
                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");

                    Map<String, String> map = new HashMap<>();
                    map.put("longitude", location.getLongitude() + "");
                    map.put("latitude", location.getLatitude() + "");
                    map.put("LocationType", location.getLocationType() + "");
                    map.put("Province", location.getProvince() + "");
                    map.put("City", location.getCity() + "");
                    map.put("District", location.getDistrict() + "");
                    map.put("Address", location.getAddress() + "");
                    map.put("time", Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "");
                    map.put("Accuracy", location.getAccuracy() + "");

                    JSONObject j = new JSONObject(map);
//                    ToastUtils.s(MainActivity.this,j.toString());
                    dWebView.callHandler("setLocation", new Object[]{j.toString()});

                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                    location.setLatitude(116.2);
                    location.setLongitude(39.56);
//                    ToastUtils.s(MainActivity.this,sb.toString());
                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
//                tvResult.setText(result);
                LogUtils.d("定位数据是" + result);
            } else {
                LogUtils.d("定位失败，loc is null");
            }
        }
    };

    private String clientId;

    @Override
    public void getClientId(Object params) {
        LogUtils.d("数据是clientId" + clientId);
        if (clientId != null) {
            dWebView.callHandler("getClientIdCallBack", new Object[]{clientId});
        }
    }

    private String getGPSStatusString(int statusCode) {
        String str = "";
        switch (statusCode) {
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        mOption.setLocationCacheEnable(true);

        return mOption;
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void initView() {
        button = findViewById(R.id.test);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                jsTakeUpload("dheueee");
                third_party_login(null);
            }
        });
        dialog = new ProgressDialog(context);
        loadView = findViewById(R.id.loadView);
        smartRefreshLayout = findViewById(R.id.refreshlayout);
        smartRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        smartRefreshLayout.setEnableOverScrollDrag(false);
        smartRefreshLayout.setEnableRefresh(false);

        dWebView = new DWebView(this);
        dWebView.addJavascriptObject(new JsApi(this), null);
        //开启浏览器调试
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && BuildConfig.DEBUG) {
            dWebView.setWebContentsDebuggingEnabled(true);
        }

        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mAgentWeb.getUrlLoader().reload();
            }
        });
        //下拉内容不偏移
        smartRefreshLayout.setEnableHeaderTranslationContent(false);

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(smartRefreshLayout, new FrameLayout.LayoutParams(-1, -1))
                .closeIndicator()
                .setWebViewClient(webViewClient)
                .setWebView(dWebView)
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)//不跳转其他应用
                .createAgentWeb()
                .ready()
                .go(url);
    }

    private void initWight() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(false); //是否按矩形区域保存
        imagePicker.setSelectLimit(6);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
        imagePicker.setMultiMode(true);   //允许剪切
    }

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (firstLoad) {
                loadView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            smartRefreshLayout.finishRefresh();
            if (firstLoad) {
                firstLoad = false;
                goneAnim(loadView);
            }
        }
    };

    private void goneAnim(final View view) {
        AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
        alphaAnimation.setDuration(700);

        view.startAnimation(alphaAnimation);
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private long exitTime = 0;

    public void doubleExit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            toast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    protected void showDig(String msg, boolean canCancel) {
        if (loadDialog == null) {
            loadDialog = new LoadDialog.Builder(this).loadText(msg).canCancel(canCancel).build();
        } else {
            loadDialog.setText(msg);
        }
        if (!loadDialog.isShowing())
            loadDialog.show();
    }

    protected void dismissDig() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    private void setStatusBg(int resId) {
        ViewGroup contentView = findViewById(android.R.id.content);
        View statusBarView = new View(this);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                Utils.getStatusBarHeight(this));
        statusBarView.setBackgroundResource(resId);
        contentView.addView(statusBarView, lp);
    }

    @Override
    public void jsGetAlipayParams(Object params) {

    }

    @Override
    public void jsTakeUpload(Object params) {
        if (params == null) {
            return;
        }
        type = "1";
        initPictandVideoone();
    }

    @Override
    public void jsTakeUploads(Object params) {
        requestUrl = "http://hbtianshou.com/paotui/riding/more";//"http://hbtianshou.com/paotui/riding/more";
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项

                .maxSelectNum(9)
                .selectionMedia(selectList)
                .forResult(CHOOSE_MANY);
    }

    final static int CHOOSE_MANY = 1997;

    private void initPictandVideoone() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .imageSpanCount(3)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .previewVideo(false)
                .enableCrop(false)
                .circleDimmedLayer(false)
                .isCamera(false)
                .selectionMedia(selectList)
                .minimumCompressSize(100)
                .isDragFrame(true)
                .forResult(CHOOSE_REQUEST);
    }

    SHARE_MEDIA id;

    @Override
    public void third_party_login(Object params) {
        //项目没有申请微信   暂时不实现
//        params = null;
//
//        if (params == null) {
//            return;
//        }
        LogUtils.d("数据是" + params.toString());
        if (params.toString().equals("5")) {// 微信
            shareMedia = SHARE_MEDIA.WEIXIN;
        } else if (params.toString().equals("2")) {// QQ
            shareMedia = SHARE_MEDIA.QQ;
        }
        UMShareAPI.get(context).getPlatformInfo(this, shareMedia, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                SocializeUtils.safeShowDialog(dialog);
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                SocializeUtils.safeCloseDialog(dialog);
                JSONObject j = new JSONObject(map);
                dWebView.callHandler("addWX", new Object[]{j.toString()});
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                SocializeUtils.safeCloseDialog(dialog);
                Toast.makeText(context, "失败：" + throwable.getMessage(), Toast.LENGTH_LONG).show();
                Log.e("onCancel: ", throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                SocializeUtils.safeCloseDialog(dialog);
                Toast.makeText(context, "取消了", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void initPictandVideo() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .imageSpanCount(3)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .previewVideo(false)
                .enableCrop(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .isCamera(true)
                .isZoomAnim(true)
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(false)
                .cropWH(600, 600)
                .withAspectRatio(1, 1)
                .selectionMedia(selectList)
                .minimumCompressSize(100)
                .isDragFrame(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    public void qr_code(Object params) {
        permissionHelper = new PermissionHelper(this, new String[]{Manifest.permission.CAMERA}, 100);
        permissionHelper.request(new PermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);

                startActivityForResult(intent, REQUEST_CODE_SCAN);
            }

            @Override
            public void onIndividualPermissionGranted(String[] grantedPermission) {
//                 Log.d(TAG, "onIndividualPermissionGranted() called with: grantedPermission = [" + TextUtils.join(",",grantedPermission) + "]");
            }

            @Override
            public void onPermissionDenied() {
//                 Log.d(TAG, "onPermissionDenied() called");
            }

            @Override
            public void onPermissionDeniedBySystem() {
//                 Log.d(TAG, "onPermissionDeniedBySystem() called");
            }
        });

    }

    @Override
    public void comparison(Object params) {
        LogUtils.d("成功是" + params.toString());


        userid = params.toString();

        initPictandVideo();
    }

    @Override
    public void alipay(Object params) {
        zhifubao();
    }

    @Override
    public void Copy(Object params) {
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        //创建ClipData对象
        ClipData clipData = ClipData.newPlainText("tahome text copy", params.toString());
        //添加ClipData对象到剪切板中
        clipboardManager.setPrimaryClip(clipData);

        toast("已复制内容到剪切板");

    }


    private int mid;

    @Override
    public void uploadImg(Object params) {
        LogUtils.d("数据是" + params.toString());
        if (params != null) {
            userid = params.toString();
        }
        type = "1";
        requestUrl = "http://hbtianshou.com/paotui/store/storeZheng";

        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项

                .selectionMode(PictureConfig.SINGLE)
                .previewImage(false)
                .selectionMedia(selectList)
                .forResult(CHOOSE_REQUEST);
    }

    @Override
    public void shareUrl(Object params) {
        UMWeb umWeb = new UMWeb(params.toString());
        umWeb.setTitle("小鸡外卖");
        umWeb.setDescription("小鸡外卖下载链接呦，戳我-->");
        umWeb.setThumb(new UMImage(MainActivity.this, R.drawable.logo));
        new ShareAction(MainActivity.this).withMedia(umWeb).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {

                    }
                }).open();
    }

    @Override
    public void identity(Object params) {
//        LogUtils.d("数据是" + params.toString());

//        TypeBean info = GsonUtil.parseJsonWithGson(params.toString(), TypeBean.class);
//        type = info.getType();
//
//        if ("2".equals(type)) {
        requestUrl = ACTION_UPLOAD_HEADIMG;
//        } else {
//            requestUrl = "";
//        }

        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项

                .maxSelectNum(1)
                .selectionMedia(selectList)
                .forResult(REQUEST_UPLOAD_HEADIMG);

    }

    @Override
    public void downloadFile(Object params) {
        String downloadurl = params.toString();

        OkGo.<File>get(downloadurl)
                .tag(this)
                .execute(new FileCallback() {
                    @Override
                    public void onSuccess(Response<File> response) {
                        LogUtils.d("文件下载" + response.body());
                        LogUtils.d("文件下载" + response.code());
                        if (response.code() == 200) {
                            toast("文件下载成功");
                        }
                    }
                });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionHelper != null) {
            permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        if (requestCode == 301) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                locationClient = new AMapLocationClient(this.getApplicationContext());
                locationOption = getDefaultOption();
                //设置定位参数
                locationClient.setLocationOption(locationOption);
                // 设置定位监听
                locationClient.setLocationListener(locationListener);
                locationClient.startLocation();

            } else {//申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        301);//自定义的code
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private void compress(List<String> paths) {
        showDig("压缩中...", false);
        final int size = paths.size();
//        final Map<String, File> map = new HashMap<>();
        final List<File> map = new ArrayList<>();

        Luban.with(context).load(paths).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(List<LocalMedia> list) {

                    }


                    @Override
                    public void onError(Throwable e) {
                        dismissDig();
                        toast("图片压缩失败");

                    }
                }).launch();
    }


    private void zhifubao() {
        OkGo.<String>post("http://hbtianshou.com/paotui/order/zhifuibao")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {
                            JSONObject j = null;
                            try {
                                j = new JSONObject(response.body());
                                String data = j.getString("data");
                                goodinfo = data;
                                start();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    private void weixin() {
        OkGo.<String>post("http://hbtianshou.com/paotui/order/fuKuan")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {
                            try {
                                JSONObject j = new JSONObject(response.body());
                                String data = j.getString("data");
                                WxPayParams wxPayParams = GsonUtil.parseJsonWithGson(data, WxPayParams.class);
                                wxPay(wxPayParams);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    private void uploadImages(
//            Map<String, File> map)
            List<File> map) {
        OkGo.<String>post("http://53i532.natappfree.cc/mall/addPhotos")
                .tag(this)
                .params("user_id", "1000000000")
                .params("token", "VVON8nUAEzg7fSsh4p194TBUQtgW-rVfU7xKzpyTWe8=")
                .addFileParams("file", map)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("数据是:" + response.body());
                        MutiltypePhotoResults results = GsonUtil.parseJsonWithGson(response.body(), MutiltypePhotoResults.class);
                        LogUtils.d("数据是" + results.getMeta().getMsg());
                        if (results.getMeta().getMsg().equals("OK")) {
                            LogUtils.d("数据是" + results.getMeta().getMsg());
                            dismissDig();
                        }
                    }
                });
    }

    /**
     * 分享
     */
    @Override
    public void addFenXinag(Object params) {
        UMWeb web = new UMWeb("http://pgyer.com/c64u");
        web.setTitle("小鸡外卖");//标题
        web.setThumb(new UMImage(this, R.drawable.logo));  //缩略图
        web.setDescription("赶紧下载小鸡外卖吧，新用户戳我有惊喜-->");//描述
        new ShareAction(MainActivity.this).withMedia(web)
                .setPlatform(SHARE_MEDIA.WEIXIN)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                        LogUtils.d("分享的是:" + share_media.toString());
                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        LogUtils.d("分享的是:" + share_media.toString());
                        Toast.makeText(context, "分享成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        LogUtils.d("分享的是:" + share_media.toString());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        LogUtils.d("分享的是:" + share_media.toString());
                    }
                }).share();

    }

    /**
     * 复制
     */
    @Override
    public void takeCopy(Object params) {
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        //创建ClipData对象
        ClipData clipData = ClipData.newPlainText("tahome text copy", params.toString());
        //添加ClipData对象到剪切板中
        clipboardManager.setPrimaryClip(clipData);

        toast("已复制内容到剪切板");

    }

    @Override
    public void takeExit(Object params) {
//        int flag = (int) params;
//        if (flag == 0) {
//            //不能退出,返回上一页
//            if (dWebView != null && dWebView.canGoBack()) {
//                dWebView.goBack();
//            }
//        } else {
//            doubleExit();
//        }
        doubleExit();
    }

    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            与上次点击返回键时刻作差
//            String substring = dWebView.getUrl().substring(dWebView.getUrl().lastIndexOf("/") + 1, dWebView.getUrl().length());
//            if (substring.equals("home") | substring.equals("verbal") | substring.equals("discussion") | substring.equals("mine")) {

            if (dWebView != null && dWebView.canGoBack()) {
                // 当网页不为空并且网页可以返回上一页的时候，网页回退
                dWebView.goBack();
                return true;
            } else {
                //  如果网页没有上一页，已经是网页的主页面了，则2秒内点击返回键两次则退出该app
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    //大于2000ms则认为是误操作，使用Toast进行提示
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    //并记录下本次点击“返回键”的时刻，以便下次进行判断
                    mExitTime = System.currentTimeMillis();
                } else {
                    //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                    System.exit(0);
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {
    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
        toast("分享成功");
    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        toast("分享失败");
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event testEvent) {
        Log.e("clientId", testEvent.toString() + testEvent.getData());
        if (testEvent.getCode() == C.EventCode.A) {
            LogUtils.d("数据是clientId" + testEvent.getData());
            clientId = testEvent.getData().toString();
        }
    }

    private boolean isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                List<String> paths = new ArrayList<>();
                LogUtils.d("数据是" + images.size());
                for (ImageItem datae : images) {
                    String headImage = datae.path;
                    paths.add(headImage);
//                    String imagename = headImage.substring(headImage.lastIndexOf("/") + 1);
                    LogUtils.d("数据是:" + headImage);
//                    testokGO();
                }
                if (paths.size() == 1) {
                    LogUtils.d("数据是" + paths);
//                    uploadAvatar(paths.get(0));
//                    File file = new File(path);
//                    File newfile = CompressHelper.getDefault(context).compressToFile(file);
//                    dWebView.callHandler("getImg", new Object[]{content});
                } else if (paths.size() > 1) {
                    LogUtils.d("数据是多选" + paths);
                    compress(paths);
                }


            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                LogUtils.d("扫一扫：" + content);
                if (!content.isEmpty()) {
                    dWebView.callHandler("qr_code_callback", new Object[]{content});
                }
//                int friendsid=Integer.valueOf(content.substring(0,content.indexOf("<")));
//                LogUtils.d("扫一扫"+friendsid);
//                int grid=Integer.valueOf(content.substring(content.indexOf("<")+1,content.lastIndexOf("<")));
//                LogUtils.d("扫一扫"+grid);
//                String reamrks=content.substring(content.lastIndexOf("<")+1,content.length());
//                LogUtils.d("扫一扫"+reamrks);
//                addfriends(friendsid,grid,reamrks);
            }
        } else if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_UPLOAD_HEADIMG:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LogUtils.d("选择图片是" + selectList.get(0).getPath());
                    if (selectList.size() > 0) {
                        for (LocalMedia media : selectList) {
                            if (isAndroidQ) {
                                uploadAvatar(media.getAndroidQToPath());
                            } else {
                                uploadAvatar(media.getPath());
                            }
                        }
                    }
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LogUtils.d("选择图片是" + selectList.get(0).getPath());
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    if (selectList.size() > 0) {
                        for (LocalMedia media : selectList) {
                            if (isAndroidQ) {
                                uploadAvatar(media.getAndroidQToPath());
                            } else {
                                uploadAvatar(media.getPath());
                            }
                        }
                    }
//                        PictureFileUtils.deleteCacheDirFile(MainActivity.this);
                    break;
                case CHOOSE_MANY:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    List<File> list = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        LocalMedia media = selectList.get(i);
                        File file;
                        if (isAndroidQ) {
                            file = new File(media.getAndroidQToPath());
                        } else {
                            file = new File(media.getPath());

                        }
                        if (file.exists()) {
                            list.add(file);
                        }
                    }
                    uploadImagess(list);
                    break;
            }
        }
    }

    private void uploadImagess(List<File> files) {
        OkGo.<String>post(requestUrl)
                .tag(this)
                .isMultipart(true)
                .addFileParams("file", files)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("成功是" + response.message());
                        if (response.code() == 200) {
                            selectList = new ArrayList<>();
                            PicBean photoBean = GsonUtil.parseJsonWithGson(response.body(), PicBean.class);
                            dWebView.callHandler("addMoneyPic", new Object[]{photoBean.getData()});
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.d("失败是是" + response.message());
                    }
                });
    }

    private void testokGO() {
        OkGo.<String>post("http://39.105.148.182/qingniaozhongchou/wdt_showgoodsdetail.do")
                .params("goodsid", 13)
                .params("userid", 0)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        TestGoodsBean s = GsonUtil.parseJsonWithGson(response.body(), GoodsDetails.class);
//                        LogUtils.d("数据是:" + s.getMsg() + s.getGoods());
                    }
                });
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        LogUtils.d("支付成功");
                        dWebView.callHandler("alipayMsg", new Object[]{"1"});
//                        finish();
//                        Intent jump_gouwuche = new Intent(GoToBuyActivity.this, MainActivity.class);
////                finish();
//                        jump_gouwuche.putExtra("jump_gouwuche", 0);
//                        startActivity(jump_gouwuche);
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(GoToBuyActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        Toast.makeText(GoToBuyActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        LogUtils.d("支付失败");
                    }
                    break;
                }
//                case SDK_AUTH_FLAG: {
//                    @SuppressWarnings("unchecked")
//                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
//                    String resultStatus = authResult.getResultStatus();
//
//                    // 判断resultStatus 为“9000”且result_code
//                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
//                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
//                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
//                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
//                    } else {
//                        // 其他状态值则为授权失败
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
//
//                    }
//                    break;
//                }
                default:
                    break;
            }
        }
    };

    private void start() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                Log.d("AAAAAAAAAAAA", goodinfo);
                PayTask alipay = new PayTask(MainActivity.this);
                Map<String, String> result = alipay.payV2(goodinfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void uploadAvatar(String path) {
        LogUtils.d("数据是" + path);
        File file = new File(path);
        File newfile = CompressHelper.getDefault(context).compressToFile(file);
        if (!newfile.exists()) {
            toast("图片不存在");
            return;
        }
        if ("1".equals(type)) {
            OkGo.<String>post(requestUrl)
                    .tag(this)
                    .isMultipart(true)
                    .params("zurl", newfile)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            if (response.code() == 200) {
                                String resultBody = response.body();
                                PhotoBean photoBean = GsonUtil.parseJsonWithGson(resultBody, PhotoBean.class);
                                dWebView.callHandler("addImgCallback", new Object[]{photoBean.getData()});
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            LogUtils.d("失败是是" + response.message());
                        }
                    });
        } else {
            OkGo.<String>post(requestUrl)
                    .tag(this)
                    .isMultipart(true)
                    .params("icon_image", newfile)
                    .params("id", userid)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            if (response.code() == 200) {
                                selectList = new ArrayList<>();
                                String resultBody = response.body();
                                UploadImgBean photoBean = GsonUtil.parseJsonWithGson(resultBody, UploadImgBean.class);
                                if (photoBean != null && photoBean.getData() != null) {
                                    if ("1".equals(photoBean.getCode() + "")) {
                                        String resultData = photoBean.getData().getUrl();
                                        if (!TextUtils.isEmpty(resultData)) {
                                            dWebView.callHandler("addHeadImgCallback", new Object[]{resultData});
                                        } else {
                                            toast("上传失败");
                                        }
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            LogUtils.d("失败是是" + response.message());
                        }
                    });
        }
    }

    private final int HANDLER_REFRESH_HEADIMG = 112;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_REFRESH_HEADIMG:
                    dWebView.callHandler("addCardImgCallback", new Object[]{"123123"});
//                    dWebView.callHandler("addCardImgCallback", new Object[]{resultStr});
                    break;
            }
        }
    };

    /**
     * 下载图片
     */
    @Override
    public void saveImg(Object params) {
        String imgUrl = params.toString();
        OkGo.<File>get(imgUrl)
                .tag(this)
                .execute(new FileCallback(FILE_DIR, Utils.getFileName(imgUrl)) {
                    @Override
                    public void onSuccess(Response<File> response) {
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.fromFile(new File(response.body().getPath()))));
                        toast("已保存到本地");
                    }

                    @Override
                    public void onError(Response<File> response) {
                        super.onError(response);
                        toast("保存出错");
                    }
                });
    }

    String FILE_DIR = Environment.getExternalStorageDirectory().getPath() + "/wlgj/picture/";

    public void saveImg1(Object params) {
        String fileUrl = params.toString();
        String destFileName = String.valueOf(System.currentTimeMillis());
        String mDestFileName = fileUrl.substring(fileUrl.lastIndexOf("."), fileUrl.length());
        OkGo.<File>get(fileUrl).tag(this).execute(new FileCallback(FILE_DIR, destFileName + mDestFileName) { //文件下载时指定下载的路径以及下载的文件的名称
            @Override
            public void onStart(Request<File, ? extends Request> request) {
                super.onStart(request);
                LogUtils.e("开始下载文件" + "DDDDD");
            }

            @Override
            public void onSuccess(com.lzy.okgo.model.Response<File> response) {
                LogUtils.e("下载文件成功" + "DDDDD" + response.body().length());
                String mBasePath = response.body().getAbsolutePath();
                File f_path = new File(mBasePath);
                if (f_path != null && f_path.exists() && f_path.isFile()) {
                    try {
                        saveBitmap(MainActivity.this, mBasePath, f_path.getName());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                LogUtils.e("下载文件完成" + "DDDDD");
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<File> response) {
                super.onError(response);
                LogUtils.e("下载文件出错" + "DDDDD" + response.message());
            }

            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                float dLProgress = progress.fraction;
                LogUtils.e("文件下载的进度" + "DDDDD" + dLProgress);
            }
        });
    }

    private void saveBitmap(Context context, String imagePath, String imagename) throws
            IOException {
        try {
            ContentResolver cr = context.getContentResolver();
            String url = MediaStore.Images.Media.insertImage(cr, imagePath, imagename, "");
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(new File(url));
            intent.setData(uri);
            context.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void zfb_pay(Object params) {
        LogUtils.d("数据是" + params.toString());
        try {
            JSONObject j = new JSONObject(params.toString());
            goodinfo = j.getString("data");
            start();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void wx_pay(Object params) {


        if (params != null) {
            try {
                JSONObject jsonObject = new JSONObject(params.toString());
                WxPayParams wxPayParams = GsonUtil.parseJsonWithGson(jsonObject.getString("data"), WxPayParams.class);
                wxPay(wxPayParams);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void uploadHeadImg(Object params) {
        LogUtils.d("数据是" + params.toString());
        if (params != null) {
            userid = params.toString();
        }
        type = "2";
        requestUrl = "http://xinlian.nxiapk.top/api/xuser/editrecommendpost";
        initPictandVideo();
    }

    /**
     * 微信支付
     *
     * @param params
     */
    private void wxPay(WxPayParams params) {
        PayReq req = new PayReq();
        req.appId = params.getAppId();
        req.partnerId = params.getPartnerId();
        req.prepayId = params.getPrepayId();
        req.packageValue = params.getPackages();
        req.nonceStr = params.getNonceStr();
        req.timeStamp = params.getTimeStamp();
        req.sign = params.getSign();
        api.sendReq(req);
    }

}
